package com.misolab.android.http;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.misolab.android.log.Logger;

public class Downloader extends PoolWorker {
	
	final static String ClassName = Downloader.class.getSimpleName();
	void logInfo(String functionName){
		Logger.i(ClassName+"::"+functionName);
	}

	public interface DownloaderListener {
		public void onSuccess(Downloader downloader, byte[] bytes);
		public void onFailure(Downloader downloader, Throwable error);
	}

	DownloaderListener listener;
	public DownloaderListener getListener() {
		logInfo("setListener");
		return listener;
	}
	public void setListener(DownloaderListener listener) {
		logInfo("setListener");
		this.listener = listener;
	}

	public Downloader(DownloaderListener listener) {
		super();
		logInfo("Downloader");
		this.listener = listener;
	}

	@Override
	public void doWork(String url) {
		logInfo("doWork");
		Logger.d(url);
		
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = null;

		try {
			httpResponse = httpClient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = httpResponse.getEntity();
				listener.onSuccess(this, EntityUtils.toByteArray(entity));
				return;
			}

			listener.onFailure(this, new Exception("HttpStatus is not Success :"
					+ httpResponse.getStatusLine().getStatusCode()));

		} catch (ClientProtocolException e1) {
			listener.onFailure(this, e1);
		} catch (IOException e1) {
			listener.onFailure(this, e1);
		}
	}

	public void download(String url) {
		logInfo("download");
		Logger.d(url);

		addRequest(url);
	}

}
